package com.yxh.www.author.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yxh.www.author.domain.SmResource;
import com.yxh.www.author.mapper.SmResourceMapper;
import com.yxh.www.author.service.SmResourceService;
import com.yxh.www.common.result.Result;
import com.yxh.www.common.result.ResultBuilder;
import com.yxh.www.common.result.ResultEnum;
import com.yxh.www.mysql.base.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 系统菜单-RBAC 服务实现类
 * </p>
 *
 * @author Yangxiaohui
 * @since 2020-05-09
 */
@Service
@Transactional
public class SmResourceServiceImpl extends BaseServiceImpl<SmResourceMapper, SmResource> implements SmResourceService {

    /**
     * 新增系统资源信息
     *
     * @param resourceTitle 资源标题    必填
     * @param resourceIcon  资源图标    非必填
     * @param resourcePath  资源路径    非必填
     * @param parentId      父级ID    非必填 默认 0：根目录
     * @param permissionKey 权限标识    非必填
     * @param resourceType  资源（0：目录；1：菜单；2：按钮）  必填
     * @return 统一响应 {@link Result}
     */
    @Override
    public Result<Object> addSmResource(String resourceTitle, String resourceIcon, String resourcePath, String parentId, String permissionKey, String resourceType) {
        // 同级目录下资源名称不能重复
        int countSmResourceByResourceTitleAndParentId = baseMapper.selectCount(new QueryWrapper<SmResource>().eq("parent_id", parentId).eq("resource_title", resourceTitle));
        if (countSmResourceByResourceTitleAndParentId > 0) {
            return ResultBuilder.error(ResultEnum.USER_HANDEL_ERROR, "同级目录不能插入重复的资源名称！");
        }
        // permissionKey 不能重复
        if (StringUtils.isNotBlank(permissionKey)) {
            int countSmResourceByPermissionKey = baseMapper.selectCount(new QueryWrapper<SmResource>().eq("permission_key", permissionKey));
            if (countSmResourceByPermissionKey > 0) {
                return ResultBuilder.error(ResultEnum.USER_HANDEL_ERROR, "重复的PermissionKey！");
            }
        }
        // 查询该资源父级下最大排序
        int maxOrderNumberByParentId = baseMapper.selectCount(new QueryWrapper<SmResource>().eq("parent_id", parentId));
        // 持久化数据
        SmResource smResource = new SmResource(resourceTitle, resourceIcon, resourcePath, parentId, permissionKey, resourceType);
        smResource.setCreateTime(LocalDateTime.now());
        smResource.setOrderNumber(maxOrderNumberByParentId);
        return smResource.insert() ? ResultBuilder.success() : ResultBuilder.error(ResultEnum.USER_HANDEL_ERROR, "系统资源新增失败！");
    }

    /**
     * 修改系统资源
     *
     * @param id             系统资源ID 必填
     * @param resourceTitle  资源标题   非必填
     * @param resourceIcon   资源图标   非必填
     * @param resourcePath   资源路径   非必填
     * @param permissionKey  权限标识   非必填
     * @param resourceStatus 资源状态（0：正常；1：失效）    非必填
     * @param orderNumber    排序编号   非必填
     * @return 统一响应 {@link Result}
     */
    @Override
    public Result<Object> modifySmResource(String id, String resourceTitle, String resourceIcon, String resourcePath, String permissionKey, String resourceStatus, Integer orderNumber) {
        // 同级目录下资源名称不能重复
        int countSmResourceByResourceTitleAndId = baseMapper.selectCount(new QueryWrapper<SmResource>().eq("resource_title", resourceTitle).eq(false, "id", id));
        if (countSmResourceByResourceTitleAndId > 0) {
            return ResultBuilder.error(ResultEnum.USER_HANDEL_ERROR, "同级目录不能插入重复的资源名称！");
        }
        // permissionKey 不能重复
        if (StringUtils.isNotBlank(permissionKey)) {
            int countSmResourceByPermissionKey = baseMapper.selectCount(new QueryWrapper<SmResource>().eq("permission_key", permissionKey).eq(false, "id", id));
            if (countSmResourceByPermissionKey > 0) {
                return ResultBuilder.error(ResultEnum.USER_HANDEL_ERROR, "重复的PermissionKey！");
            }
        }
        SmResource smResource = new SmResource(id, resourceTitle, resourceIcon, resourcePath, permissionKey, resourceStatus, orderNumber);
        return smResource.updateById() ? ResultBuilder.success() : ResultBuilder.error(ResultEnum.USER_HANDEL_ERROR, "修改系统资源失败");
    }

    /**
     * 根据ID删除系统资源
     *
     * @param ids 资源ID集合
     * @return 统一响应 {@link Result}
     */
    @Override
    public Result<Object> removeSmResource(String[] ids) {
        baseMapper.deleteBatchIds(Arrays.asList(ids));
        return ResultBuilder.success();
    }

    /**
     * 查询系统资源列表
     *
     * @param resourceTitle 资源标题 模糊查询
     * @param resourcePath  资源路径 模糊查询
     * @return 统一响应 {@link Result<  List  >} 实体 {@link SmResource}
     */
    @Override
    public Result<List<SmResource>> listSmResource(String resourceTitle, String resourcePath) {
        return ResultBuilder.success(baseMapper.selectList(this.buildSmResourceListQuery(resourceTitle, resourcePath)));
    }

    /**
     * 分页查询系统资源列表
     *
     * @param resourceTitle 资源标题 模糊查询
     * @param resourcePath  资源路径 模糊查询
     * @param pageNum       页码          默认值 1
     * @param pageSize      页面数据长度    默认值 20
     * @return 统一响应 {@link Result}
     */
    @Override
    public Result<Object> pageSmResource(String resourceTitle, String resourcePath, Long pageNum, Long pageSize) {
        return ResultBuilder.success(baseMapper.selectPage(new Page<>(pageNum, pageSize), this.buildSmResourceListQuery(resourceTitle, resourcePath)));
    }

    /**
     * 构建系统资源列表查询QueryWrapper
     *
     * @param resourceTitle 资源标题 模糊查询
     * @param resourcePath  资源路径 模糊查询
     * @return {@link QueryWrapper}
     */
    private QueryWrapper<SmResource> buildSmResourceListQuery(String resourceTitle, String resourcePath) {
        QueryWrapper<SmResource> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(resourceTitle)) {
            queryWrapper.like("resource_title", resourceTitle);
        }
        if (StringUtils.isNotBlank(resourcePath)) {
            queryWrapper.like("resource_path", resourcePath);
        }
        queryWrapper.orderByAsc("order_number");
        return queryWrapper;
    }
}
